package com.xnyzc.lhy.statistics.component.es;

import com.xnyzc.lhy.common.util.DateUtil;
import io.searchbox.action.Action;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * ES jestClient服务类
 *
 * @author cuixiaojian
 */
@Slf4j
@Component
public class JestService {

    @Autowired
    private JestClient jestClient;

    /**
     * 执行
     * @param o 泛型
     * @return JestResult
     */
    public JestResult jestExecute(Action<?> o) {
        JestResult jestResult = null;
        try {
            jestResult = jestClient.execute(o);
            log.info("ES普通查询响应JSON为：{}", jestResult.getJsonString());
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return jestResult;
    }

    /**
     * 聚合执行
     * @param search Search
     * @return SearchResult
     */
    public SearchResult searchExecute(Search search) {
        SearchResult searchResult = null;
        try {
            searchResult = jestClient.execute(search);
            log.info("ES聚合查询响应JSON为：{}", searchResult.getJsonString());
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return searchResult;
    }

    /**
     * 追加今日条件
     *
     * boolQuery must toDays
     */
    public void addToDay(BoolQueryBuilder queryBuilder, String field) {
        Date now = new Date();
        String toDay = DateUtil.convertToStringCustom(now, "yyyy-MM-dd");
        String toDayAddOne = DateUtil.convertToStringCustom(DateUtil.dateAddDays(now, 1), "yyyy-MM-dd");
        queryBuilder.must(QueryBuilders.rangeQuery(field).gte(DateUtil.convertStringToDate(toDay + " 08:00:00")).lte(DateUtil.convertStringToDate(toDayAddOne + " 07:59:59")));
    }

    /**
     * 轨迹查询
     *
     * matchQuery
     */
    public JestResult trajectoryMatchQuery(String field, String value, String indexName, String type) {

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().fetchSource(new String [] {"lng", "lat"}, null);

        searchSourceBuilder.from(0);
        searchSourceBuilder.size(10000);

        searchSourceBuilder.query(QueryBuilders.matchQuery(field,value));

        Search search = new Search.Builder(searchSourceBuilder.toString())
                .addIndex(indexName).addType(type).build();

        log.info("轨迹查询执行语句:{}", searchSourceBuilder.toString());

        return jestExecute(search);

    }

}
